package com.kaiyidiannao.activity.foodpalace;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.kaiyidiannao.adapter.CommonViewpagerAdapter;
import com.kaiyidiannao.common.BaseActionBarActivity;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.https.HttpUtils;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.PlayBean;
import com.kaiyidiannao.model.req.model.GetFoodPalaceShow;
import com.kaiyidiannao.model.req.model.PostAddFavorites;
import com.kaiyidiannao.view.ActionBarView;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by mark on 2014/4/9.
 */
public class FoodPalaceDetail extends BaseActionBarActivity implements View.OnClickListener, Observer {
    //    private RatingBar ratingBar;
//    private TextView ratingScore;
    //    private Button commentButton;
    private ImageView storeCall;
    private ImageView coupon;
    private TextView sellerPhoneNum;
    private TextView storeName;
    private TextView sellerAddr;
    private TextView sellerDetails;
    private PlayBean bean;
    private ImageView collect;
    private LinearLayout coupons;
    private String userid;
    private ViewPager foodDetailViewPager;
    private boolean collectFlag;
    private String itemid;
    private int catid;
//    private int module_type; //模块区分编号

    /**
     * 初始化8张详情图片
     */
    private ViewPager detailViewPager;
    private CommonViewpagerAdapter commonViewpagerAdapter;
    private List<View> imageList = new ArrayList<View>();
    private List<String> imageUrlList = new ArrayList<String>();
    private ImageView imageView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.food_detail);
        DataCenter.getInstance().addObserver(this);

        findId();
        // 请求的数据
        showProgressDialog();
        itemid = getIntent().getStringExtra("itemid");
        // 详情的catid是固定的
        try {
            catid = Integer.parseInt(getIntent().getStringExtra("catid"));
        } catch (NumberFormatException e) {
            catid = getIntent().getIntExtra("catid", 0);
        }
        if (catid >= 16 && catid <= 31) {
            catid = 16;
        } else if (catid >= 32 && catid <= 48) {
            catid = 32;
        }
//        module_type = getIntent().getIntExtra("module_type", FoodPalaceActivity.MODLUE_BUY_STREET );
        if (isLogin()) {
            userid = getUserid();
            try {
                new GetFoodPalaceShow(Integer.parseInt(itemid), userid, catid + "").execute();
            } catch (NumberFormatException e) {

            }
        } else {
            try {
                new GetFoodPalaceShow(Integer.parseInt(itemid), catid + "").execute();
            } catch (Exception e) {

            }
        }
//        commentButton.setOnClickListener(this);
        storeCall.setOnClickListener(this);
        collect.setOnClickListener(this);
        findActionBar();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DataCenter.getInstance().deleteObserver(this);
//        DataCenter.foodPalaceList.clear();
    }

    private void findId() {
        collect = (ImageView) findViewById(R.id.collect);
//        commentButton = (Button) findViewById(R.id.commentButton);
        storeName = (TextView) findViewById(R.id.storeName);
        storeCall = (ImageView) findViewById(R.id.storeCall);
        sellerAddr = (TextView) findViewById(R.id.sellerAddr);
        sellerPhoneNum = (TextView) findViewById(R.id.sellerPhoneNum);
        coupons = (LinearLayout)findViewById(R.id.coupons);
//        ratingBar = (RatingBar)findViewById(R.id.rating1);
//        ratingScore = (TextView) findViewById(R.id.ratingScore);
        sellerDetails = (TextView) findViewById(R.id.sellerDetails);
        detailViewPager = (ViewPager) findViewById(R.id.foodDetailViewPager);
        imageView = (ImageView) findViewById(R.id.coupon);
    }

    private void initId() {
        initImageList();
        storeName.setText(bean.getTitle());
        sellerAddr.setText(bean.getAddress());
        sellerPhoneNum.setText(bean.getTelephone() + "");
        sellerDetails.setText(bean.getIntroduce() + "");
        Log.d("initId", bean.getStar() + "");
//        ratingBar.setRating(Float.parseFloat(bean.getStar()));
//        ratingScore.setText(bean.getStar());
        if (bean.isIs_fav()) {// 已经收藏
            collect.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.shoucanged));
        } else if (!bean.isIs_fav()) {
            collect.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.shoucang));
        }
        foodDetailViewPager = (ViewPager) findViewById(R.id.foodDetailViewPager);
        commonViewpagerAdapter = new CommonViewpagerAdapter(FoodPalaceDetail.this, imageList, foodDetailViewPager, imageUrlList);
    }

    private void findActionBar() {
        actionBarView = (ActionBarView) findViewById(R.id.actionbar);
        actionBarView.setTitle("商家详情");
//        actionBarView.button_right_icon2.setVisibility(View.VISIBLE);
//        actionBarView.button_right_icon2.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.error_recovery));
    }

    @Override
    public void onClick(View v) {
        if(!HttpUtils.isConnected()){
            Toast.makeText(FoodPalaceDetail.this,"网络连接异常,请稍后重试",Toast.LENGTH_SHORT).show();
            return;
        }
        if (null != bean) {
            if (isLogin()) {
                switch (v.getId()) {
//                    case R.id.commentButton:
//                        Intent intent = new Intent(FoodPalaceDetail.this, StarComment.class);
//                        startActivity(intent);
//                        break;
                    case R.id.storeCall:
                        String phoneNum = (String) sellerPhoneNum.getText();
                        Intent intent1 = new Intent();
                        intent1.setAction(Intent.ACTION_CALL);
                        intent1.setData(Uri.parse("tel:" + phoneNum));
                        startActivity(intent1);
                        break;
                    case R.id.collect://我的收藏
                        showProgressDialog();
                        String action = "add";
                        if (bean.isIs_fav()) {
                            action = "delete";
                        }
                        if (catid == 16) {
                            //美食城catid是固定的16
                            new PostAddFavorites(DataCenter.CATID_FOOD_PALACE, userid, action, bean.getItemid(), bean.getTitle()).execute();
                        } else if (catid == 32) {
                            //石子街catid是固定的32
                            new PostAddFavorites(DataCenter.CATID_BUY_STREAT, userid, action, bean.getItemid(), bean.getTitle()).execute();
                        }
                        collect.setEnabled(false);
                        break;
                }
            } else {
                startLoginOrRegistered();
            }
        } else {
            showToast("详情加载失败");
        }
    }

    private void initViewPage() {
        commonViewpagerAdapter = new CommonViewpagerAdapter(FoodPalaceDetail.this, imageList, detailViewPager, imageUrlList);

        for (int i = 0; i < imageUrlList.size(); i++) {
            final int position = i;
            View view = getLayoutInflater().inflate(R.layout.common_viewpager_item, null);
            final ImageView viewpagerItemIv = (ImageView) view.findViewById(R.id.viewpagerItemIv);
            viewpagerItemIv.setImageResource(android.R.color.white);
            imageLoader.displayImage(imageUrlList.get(i), viewpagerItemIv, super.options, null);
            viewpagerItemIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    Intent intent = new Intent();
//                    intent.setClass(SecondHandCarDetail.this, DisplayActivity.class);
//                    intent.putExtra("url", imageUrlList.get(position));
//                    startActivity(intent);
                    FoodPalaceDetail.super.startImagePagerActivity(position, bean.getPicture());
                }
            });
            imageList.add(view);
        }
        detailViewPager.setAdapter(commonViewpagerAdapter);
    }

    public void initImageList() {
        for (int i = 0; i < imageUrlList.size(); i++) {
            final int position = i;
            View view = getLayoutInflater().inflate(R.layout.common_viewpager_item, null);
            ImageView viewpagerItemIv = (ImageView) view.findViewById(R.id.viewpagerItemIv);
            imageLoader.displayImage(imageUrlList.get(i), viewpagerItemIv);
            viewpagerItemIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.setClass(FoodPalaceDetail.this, DisplayActivity.class);
                    intent.putExtra("url", imageUrlList.get(position));
                    startActivity(intent);
                }
            });
            imageList.add(view);
        }
    }

    /**
     * 显示重新加载页面
     */
    private void showReloadView() {
        findViewById(R.id.food_detail_scrollview).setVisibility(View.GONE);
        findViewById(R.id.realod_layout).setVisibility(View.VISIBLE);
        findViewById(R.id.reload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                findViewById(R.id.food_detail_scrollview).setVisibility(View.INVISIBLE);
                findViewById(R.id.realod_layout).setVisibility(View.GONE);
                showProgressDialog();
                if (isLogin()) {
                    userid = getUserid();
                    new GetFoodPalaceShow(Integer.parseInt(itemid), userid, catid + "").execute();
                } else {
                    new GetFoodPalaceShow(Integer.parseInt(itemid), catid + "").execute();
                }
            }
        });
    }

    @Override
    public void update(Observable observable, Object data) {
        DataCenter.flag flag = (DataCenter.flag) data;
        if (flag == DataCenter.flag.GET_PLAY_SHOW_SUCCESS) {
            closeProgressDialog();
            collect.setEnabled(true);
            bean = DataCenter.foodPalaceList.get(0);
            if (bean != null) {
                if (bean.getPicture().length == 0) {
                    detailViewPager.setBackgroundResource(R.drawable.ic_default);
                }
            }
            initId();
            findViewById(R.id.food_detail_scrollview).setVisibility(View.VISIBLE);
            //八张详情图片
            imageUrlList = bean.getPicture2();
            initViewPage();
            String url = bean.getYhpic();
            Log.d("String url", url);
            if (TextUtils.isEmpty(url)) {
                coupons.setVisibility(View.GONE);
                imageView.setVisibility(View.GONE);
            } else {
                imageLoader.displayImage(bean.getYhpic(), imageView, options, null);
            }
        } else if (flag == DataCenter.flag.GET_PLAY_SHOW_FAILED) { // 详情页面加载失败
            closeProgressDialog();
            showReloadView();
        }

        if (flag == DataCenter.flag.GetAddMESSAGEINFO_SUCCESS) {//收藏成功,关注成功\
            if (DataCenter.code.equals(DataCenter.successFlag)) {
                if (bean.isIs_fav()) {//从当前的关注状态变成没有关注
                    showToast(R.string.collect_cancle);
                    collect.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.shoucang));
                } else {
                    showToast(R.string.collect_add);
                    collect.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.shoucanged));
                }
                if (isLogin()) {
                    userid = getUserid();
                    try {
                        new GetFoodPalaceShow(Integer.parseInt(itemid), userid, catid + "").execute();
                    } catch (NumberFormatException e) {

                    }
                } else {
                    try {
                        new GetFoodPalaceShow(Integer.parseInt(itemid), catid + "").execute();
                    } catch (Exception e) {

                    }
                    showProgressDialog();
                }
            } else {
                showToast(DataCenter.msg, "收藏出现错误");
            }
        }
    }
}
